﻿#include "settings.h"
#include <QTextCodec>


Settings::Settings(const QString fileName, QSettings::Format format, QObject *parent)
{
    m_setting = new QSettings(fileName, format, parent);
    m_setting->setIniCodec(QTextCodec::codecForName("GB2312"));   //在此添加设置，即可读写ini文件中的中文
}

Settings::~Settings()
{
    if(m_setting)
    {
        delete m_setting;
        m_setting = Q_NULLPTR;
    }
}

void Settings::setValue(const QString group, const QString key, const QVariant value)
{
    m_mutex.lock();
    m_setting->beginGroup(group);
    m_setting->setValue(key, value);
    m_setting->sync();
    m_setting->endGroup();
    m_mutex.unlock();
}

QVariant Settings::getValue(const QString group, const QString key, const QVariant defaultValue)
{
    m_mutex.lock();
    m_setting->beginGroup(group);
    QVariant ret = m_setting->value(key, defaultValue);
    m_setting->endGroup();
    m_mutex.unlock();
    return ret;
}

void Settings::remove(const QString group, const QString key)
{
    m_mutex.lock();
    m_setting->beginGroup(group);
    m_setting->remove(key);
    m_setting->sync();
    m_setting->endGroup();
    m_mutex.unlock();
}

void Settings::remove(const QString groupAndkey)
{
    m_mutex.lock();
    m_setting->remove(groupAndkey);
    m_setting->sync();
    m_mutex.unlock();
}

bool Settings::GetFirstNodeInfo(const QString group,QString & key,QVariant & value)
{
    key.clear();
    value.clear();
    bool bRet = false;

    m_mutex.lock();
    m_setting->beginGroup(group);

    QStringList keys = m_setting->childKeys();
    if(keys.size() <= 0)
    {
        bRet = false;
    }
    else
    {
        bRet = true;
        key = keys.at(0);
        value = m_setting->value(key, value);
    }

    m_setting->endGroup();
    m_mutex.unlock();

    return bRet;
}

QSettings *Settings::getQSettings()
{
    return m_setting;
}
